<?php
/**
 * sku日销售额（每日）
 * User: bgl
 * Date: 2022/11/18
 * Time: 10:18
 */

namespace App\Admin\Controllers\SalesReport;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\RakutenAccount;
use App\Models\Basics\ShopifyAccount;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatAccount;
use App\Models\SalesReport\DailyAmount;
use App\Models\SalesReport\DailySa;
use App\Models\SalesReport\DailySv;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DailyAmountController extends AdminController{

    protected $title = '日销售额统计(RMB)';

    protected $filters = [
        'plat_id' => null,
        'area_id' => null,
        'country_id' => null,
        'account_id' => null,
        'less_than' => null,
        'greater_than' => null,
    ];

    protected function grid(){

        $grid = new Grid(new DailySa());

        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);

        $platId = $filters['plat_id'];
        $areaId = $filters['area_id'];
        $countryId = $filters['country_id'];
        $accountId = $filters['account_id'];

        $startTime = $filters['greater_than'] ?? date('Y-m-d', strtotime('-31 days'));
        $endTime   = $filters['less_than'] ?? date('Y-m-d', strtotime('-1 days'));
        $endTime = DailySv::checkLessThan($endTime);
        $startTime = DailySv::checkGreaterThan($startTime,$endTime);

        $days = formatDiffDateDay($startTime, $endTime); //天数
        $timeMax = $endTime; //最大可回推时间 (参照时间，最大可生成日期)
        $grid->model()->collection(function (Collection $collection) use($startTime, $endTime, $timeMax, $days) {
            foreach($collection as $item) {
                $dayAmountArray = DailyAmount::getDaysAmount($startTime, $endTime, $item->plat_id, $item->account_id, $item->country_id);
                $daysTotal = 0;
                for($i = $days; $i >= 0; $i--){
                    $dateTitle = date("Y-m-d", strtotime("$timeMax -$i day")); //赋值,日期格式 (1970-01-01)
                    if(array_key_exists($dateTitle, $dayAmountArray)){
                        $item->{$dateTitle} = $dayAmountArray[$dateTitle]; //赋值,当期销售额(当天)
                        $daysTotal += $item->{$dateTitle};
                    }else{
                        $item->{$dateTitle} = 0;
                    }
                }
                $item->amount = $daysTotal; //区间总量
            }
            return $collection;
        });
        $grid->column('account_id','账号')->display(function ($value){
            $account = '';
            if ($this->plat_id == SysPlat::PLAT_AMAZON) {
                $account = AmazonAccount::getAccountById($value) ?? '';
            }
            if ($this->plat_id == SysPlat::PLAT_SHOPIFY) {
                $account = ShopifyAccount::getAccountById($value) ?? '';
            }
            if ($this->plat_id == SysPlat::PLAT_RAKUTEN) {
                $account = RakutenAccount::getAccountById($value) ?? '';
            }
            return $account;
        })->totalRow('TTL');
        $grid->column('plat.title','平台');
        $grid->column('area.area','站点');
        $grid->column('country.country','国家');
        $grid->column('amount', '销售额和');

        //时间段内的销售额汇总
        $daysAmountSum = DailyAmount::getDaysAmountSum($startTime, $endTime, $platId, $accountId, $countryId, $areaId);
        //获取平均销售额汇总
        $avgDaySum = DailySa::getAvgDaySum($platId, $accountId, $countryId, $areaId);
        $avg3Sum = $avgDaySum->avg3 ?: 0;
        $avg7Sum = $avgDaySum->avg7 ?: 0;
        $avg15Sum = $avgDaySum->avg15 ?: 0;
        $avg30Sum = $avgDaySum->avg30 ?: 0;
        $salesStatus = DailySv::getSalesStatus($avg3Sum, $avg7Sum, $avg15Sum, $avg30Sum);
        $avgSum = DailySv::getWeightAvg($avg3Sum, $avg7Sum, $avg15Sum, $avg30Sum, $salesStatus);
        $salesStatusValue = DailySv::$_salesStatus[$salesStatus]; //销售趋势(总计)

        $script = <<<SCRIPT
            $(function($){
                $(".table tfoot:first").find('.column-amount').text({$daysAmountSum});

                $(".table tfoot:first").find('.column-avg3').text({$avg3Sum});
                $(".table tfoot:first").find('.column-avg7').text({$avg7Sum});
                $(".table tfoot:first").find('.column-avg15').text({$avg15Sum});
                $(".table tfoot:first").find('.column-avg30').text({$avg30Sum});
                $(".table tfoot:first").find('.column-avg').text({$avgSum});
                $(".table tfoot:first").find('.column-sales_status').text('{$salesStatusValue}');
            });
SCRIPT;
        Admin::script($script);

        for($i = $days; $i >= 0; $i--){
            $dayTitle = date("Y-m-d", strtotime("$timeMax -$i day"));
            $grid->column($dayTitle, $dayTitle); //日期格式 (1970-01-01)
            //当日的销售额汇总
            $dayAmountSum = DailyAmount::getDayAmountSum($dayTitle, $platId, $accountId, $countryId, $areaId);

            $script = <<<SCRIPT
            $(function($){
                $(".table tfoot:first").css({'color':'red'});
                $(".table tfoot:first").find('.column-{$dayTitle}').text({$dayAmountSum});
            });
SCRIPT;
            Admin::script($script);
        }
        $grid->column('avg3', '3天AVG');
        $grid->column('avg7', '7天AVG');
        $grid->column('avg15','15天AVG');
        $grid->column('avg30','30天AVG');
        $grid->column('avg','AVG');
        $grid->column('sales_status','销售趋势')->display(function ($value){
            return $value ? DailySv::$_salesStatus[$value] : '';
        });

        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('sales-report/daily-amount-download'));
        });

        $grid->fixColumns(4, 0);
        $grid->paginate(10);
        $grid->expandFilter();
        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->equal('account_id', '账号')->select(SysPlatAccount::getPlatAccountArray());
                $filter->gt('greater_than', '日期')->date();
                $filter->lt('less_than', '日期')->date();
            });
            $filter->column(1/2, function ($filter){
                $filter->equal('plat_id','平台')->select(SysPlat::$_platformNormal);
                $filter->equal('area_id','站点')->select(SysArea::options());
                $filter->equal('country_id','国家')->select(SysCountry::options());
            });
        });
        return $grid;
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $platId = $filters['plat_id'];
        $areaId = $filters['area_id'];
        $countryId = $filters['country_id'];
        $accountId = $filters['account_id'];

        $startTime = $filters['greater_than'] ?? date('Y-m-d', strtotime('-31 days'));
        $endTime   = $filters['less_than'] ?? date('Y-m-d', strtotime('-1 day'));
        $endTime = DailySv::checkLessThan($endTime);
        $startTime = DailySv::checkGreaterThan($startTime,$endTime);

        $queryExport = DailySa::query();
        if ($platId) $queryExport->where('plat_id', $platId);
        if ($areaId) $queryExport->where('area_id', $areaId);
        if ($accountId) $queryExport->where('account_id', $accountId);
        if ($countryId) $queryExport->where('country_id', $countryId);
        $this->_exeDownload($queryExport, $startTime, $endTime);
    }

    private function _exeDownload($queryExport, $startTime, $endTime){
        $days = formatDiffDateDay($startTime, $endTime); //天数
        $timeMax = $endTime; //最大可回推时间 (参照时间，最大可生成日期)
        $title1 = ['账号','平台','站点','国家','销售额和'];
        $title2 = [];
        for($i = $days; $i >= 0; $i--){
            $title2[] = date("Y.m.d", strtotime("$timeMax -$i day"));
        }
        $title3 = ['3天AVG','7天AVG','15天AVG','30天AVG','AVG','销售额趋势',];
        $head = array_merge($title1, $title2,$title3);
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="(平台)日销售额统计(RMB).csv"',
        ]);
        $response->setCallback(function () use ($head, $queryExport, $days, $startTime, $endTime, $timeMax) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $queryExport->orderBy('id', 'DESC')->chunk(500, function ($re) use ($fp, $days, $startTime, $endTime, $timeMax){
                $data = DailySa::getDownloadData($re, $days, $startTime, $endTime, $timeMax);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

}
